package fastcsv;

import java.util.*;

/**
 * A simple yet powerful timer that can record multiple time in a computing process.
 * 
 * @author Wei Hao
 *
 */
public class StopWatch {

	public static void main(String[] argd) throws InterruptedException {
		StopWatch sw = new StopWatch();
		sw.start("loading");
		Thread.sleep(10);
		sw.lap("processing");
		Thread.sleep(10);
		sw.lap("saving");
		Thread.sleep(10);
		sw.stop();
		System.out.println(sw.allTimeToString());
	}

	// Public properties
	public boolean isRunning = false;

	ArrayList<TimeSpan> times = new ArrayList<TimeSpan>();
	TimeSpan ts = null;

	public StopWatch() {

	}

	public void reset() {
		isRunning = false;
		times.clear();
	}

	/**
	 * restart = reset + start;
	 */
	public void restart(String title) {
		// reset();
		start(title);
	}

	public void start(String title) {
		if (!isRunning) {
			isRunning = true;
			ts = new TimeSpan();
			ts.title = title;
			ts.setStart();
		}
	}

	public void stop() {
		if (!isRunning)
			return;
		isRunning = false;
		ts.setEnd();
		times.add(ts);
	}

	public void lap(String title) {
		stop();
		restart(title);
	}

	public void showMilliseconds() {
		for (int i = 0; i < times.size(); i++) {
			System.out.println(times.get(i));
		}
	}

	public double getTimespan() {
		return getTimespan(0);
	}

	public double getTimespan(int i) {
		if (times.size() == 0)
			return -1;

		return times.get(i).getMillisencond();
	}

	public String allTimeToString() {
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < times.size(); i++)
			sb.append(String.format("%s=%.0f,", times.get(i).title, times.get(i).getMillisencond()));
		return sb.toString();
	}

}
